# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

from types import FunctionType, ListType

from pylons import request, url

from chowa.lib.base import render, Session
from chowa.lib.site.layout import PanelComponent
from chowa.model import Menu as MenuModel, MenuItem, MenuTopItem, MenuSubItem

class Menu(object):
    __metaclass__ = PanelComponent
    
    def __init__(self, options={}):
        self.id = None
        if options.has_key('id'):
            self.id = options['id']
    
    def render(self):
        if self.id is None:
            return ''
        else:
            menu = Session.query(MenuModel).get(self.id)
            top_items = Session.query(MenuTopItem).filter_by(menu_id=self.id).all()
            return render('/navigation/menu.html', extra_vars={'menu': menu, 'top_items':top_items})


class StaticMenus(object):
    __metaclass__ = PanelComponent
    
    def __init__(self, options={}):
        pass
    
    def render(self):
        controller = request.environ['pylons.controller']
        
        menus = []
        try:
            menu = getattr(controller, '__menus__')
            menus += menu() if type(menu) == FunctionType else menu
        except:
            pass
        
        segments = controller.__module__.split('.')
        for depth in range(2, len(segments)):
            pkg = '.'.join(segments[:depth])
            try:
                pkg_module = __import__(pkg, fromlist=['__menus__'])
                menu = getattr(pkg_module, '__menus__')
                menus += menu() if type(menu) == FunctionType else menu
            except:
                pass        
        output = ''
        for menu in menus:
            if not menu.protector or menu.protector.is_met(request.environ):
                top_items = []
                for item in menu.items:
                    
                    class ItemContext(object):
                        url = item.get_url()
                        caption = item.caption
                        is_current = item.verify()
                        subitems = []
                    
                    top_items += [ItemContext()]
                output += render('/navigation/menu.html', extra_vars={'menu': menu, 'top_items':top_items})
        return output
